//
//  CLComponentRuntimeUtils.m
//  ComponentLinkDemo
//
//  Created by newworld on 2017/3/2.
//  Copyright © 2017年 zhenby. All rights reserved.
//

#import "CLComponentRuntimeUtils.h"

@implementation CLComponentRuntimeUtils

+ (Class) classWithName:(NSString *)className withLoad:(BOOL)load
{
    Class clazz = NULL;
    if (load) {
        //call class callback
        clazz = objc_getClass(className.UTF8String);
    }else{
        //just search
        clazz = objc_lookUpClass(className.UTF8String);
    }
    
    return clazz;
}

+ (NSSet *) propertyNameForClass:(Class)clazz
{
    NSSet *properties = nil;
    
    if (!clazz || clazz == NSObject.class || clazz == [NSNull null]) {
        return properties;
    }
    
    unsigned int propertyCount = 0;
    objc_property_t *clazzProperties = class_copyPropertyList(clazz, &propertyCount);
    NSMutableDictionary *propertyNameAndClass = [NSMutableDictionary dictionary];
    for (unsigned int index = 0; index<propertyCount; index++) {
        objc_property_t property = clazzProperties[index];
        const char *propertyName = property_getName(property);
        if (propertyName) {
            NSString *name = [NSString stringWithUTF8String:propertyName];
            id propertyClass = (id)[self classOfProperty:property] ?: [NSNull null];
            propertyNameAndClass[name] = propertyClass;
        }
    }
    free(clazzProperties);
    
    
    properties = [NSSet setWithArray:propertyNameAndClass.allKeys];

    return properties;
    
}

+ (Class) classOfProperty:(objc_property_t)property
{
    NSString* propertyAttributesDescription = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
    NSArray* splitPropertyAttributes = [propertyAttributesDescription componentsSeparatedByString:@"\""];
    if ( [propertyAttributesDescription hasPrefix:@"T@"] && [splitPropertyAttributes count] > 1 ) {
        return [self classWithName:splitPropertyAttributes[1] withLoad:NO];
    } else {
        return nil;
    }
}


+ (BOOL) doesClass:(Class)clazz hasProperty:(NSString *)propertyName
{
    BOOL hasProperty = NO;
    
    
    return hasProperty;
}




@end
